package services

import (
	"encoding/base64"
	"gitee.com/zhoulvvv/my_go_gateway/dto"
	"gitee.com/zhoulvvv/my_go_gateway/public"
	"github.com/dgrijalva/jwt-go"
	"github.com/e421083458/golang_common/lib"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"gorm.io/gorm"
	"log"
	"strings"
	"time"
)

type OAuthServices struct {
	tx *gorm.DB
}

func (s OAuthServices) GetTokens(c *gin.Context, params *dto.TokensInput) (*dto.TokensOutput, error) {
	splits := strings.Split(c.GetHeader("Authorization"), " ")
	if len(splits) != 2 {
		return nil, errors.New("用户名或者密码格式错误")
	}
	appSecret, err := base64.StdEncoding.DecodeString(splits[1])
	if err != nil {
		return nil, errors.New("Base64解密密码错误：" + err.Error())
	}
	log.Printf("appSecret: %s", appSecret)
	// 1、取出app_id secret
	// appSecretSplits[0] 是 appId appSecretSplits[1] 是 secret
	appSecretSplits := strings.Split(string(appSecret), ":")
	if len(appSecretSplits) != 2 {
		return nil, errors.New("appSecretSplits用户名或者密码格式错误")
	}
	// 2、获取到内存中租户的信息
	appList := AppManagerHandler.GetAppList()
	// 3、匹配app_id
	for _, item := range appList {
		if item.AppId == appSecretSplits[0] && item.Secret == appSecretSplits[1] {
			// 4、基于jwt生成token
			claims := jwt.StandardClaims{
				ExpiresAt: time.Now().Add(public.JwtExpires * time.Second).In(lib.TimeLocation).Unix(),
				Issuer:    item.AppId,
			}
			token, err := public.JwtEncode(claims)
			if err != nil {
				return nil, errors.New("token生成失败：" + err.Error())
			}
			output := &dto.TokensOutput{
				AccessToken: token,
				ExpiresIn:   public.JwtExpires,
				TokenType:   "Bearer",
				Scope:       "read_write",
			}
			return output, nil
		}
	}
	return nil, errors.New("获取token失败，没有找到对应的用户信息")
}

func NewOAuthServices() (*OAuthServices, error) {
	tx, err := lib.GetGormPool("default")
	if err != nil {
		return nil, errors.New("获取数据库连接池失败")
	}
	return &OAuthServices{tx: tx}, nil
}
